package com.mnb.beidou.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mnb.beidou.model.ModbusDataEntity;
import com.mnb.beidou.model.PSDataEntity;
import com.mnb.beidou.service.TcpMessageService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * TCP服务器通道处理器
 */
@Component
public class TcpServerChannelHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(TcpServerChannelHandler.class);

    private final TcpMessageService messageService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public TcpServerChannelHandler(TcpMessageService messageService) {
        this.messageService = messageService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        InetSocketAddress address = channel.remoteAddress();

        logger.info("客户端连接: {}:{}", address.getAddress().getHostAddress(), address.getPort());


        sendMessage(ctx, "连接成功！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        InetSocketAddress address = channel.remoteAddress();

        logger.info("客户端断开连接: {}:{}", address.getAddress().getHostAddress(), address.getPort());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof String) {
            String messageStr = (String) msg;
            logger.debug("收到原始消息: {}", messageStr);
            messageStr = messageStr.replace(" ", "");
            try {
                // 处理消息
                PSDataEntity entity = messageService.processMessage(messageStr, null);
                if (entity != null) {
                    // sendMessage(ctx, response);
                }


            } catch (Exception e) {
                logger.error("处理消息时发生错误: {}", messageStr, e);

            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("通道异常", cause);
        ctx.close();
    }


    /**
     * 发送消息
     *
     * @param ctx     通道上下文
     * @param message 消息对象
     */
    private void sendMessage(ChannelHandlerContext ctx, String message) {
        try {
            String jsonMessage = objectMapper.writeValueAsString(message);
            ctx.writeAndFlush(jsonMessage);

            logger.debug("发送消息: {}", jsonMessage);

        } catch (Exception e) {
            logger.error("发送消息失败", e);
        }
    }

}
